package openones.samples.dataform.control;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import openones.corewa.BaseOutForm;
import openones.corewa.ReqUtil;
import openones.corewa.validate.config.CheckType;
import openones.corewa.validate.config.ValidationConf;
import openones.samples.dataform.biz.DataFormBiz;
import openones.samples.dataform.form.AddInForm;

import org.apache.log4j.Logger;

import rocky.common.CommonUtil;
import rocky.common.Constant;
import rocky.mvcportlet.control.BaseControl;

public class AddControl extends BaseControl {
    private static final String K_MESSAGE = "MESSAGE";
    private static final String K_ERROR = "ERROR";
    
    /** Default date format: dd/MM/yyyy. */
    private static final String DATE_FMT = Constant.VN_DATEFMT;
    static final Logger LOG = Logger.getLogger("AddControl");

    /**
     * Initial screen Add.
     */
    @Override
    public BaseOutForm init(RenderRequest request, RenderResponse response) throws PortletException, IOException {
        BaseOutForm outForm = new BaseOutForm();
        
        AddInForm initForm = new AddInForm();

        // Init the current day for birthday field
        initForm.setBirthday(CommonUtil.formatDate(new Date(), DATE_FMT));
        
        // Create data for initial screen Add. View default value of properties in AddInForm
        outForm.putRequest(AddInForm.FORM_BEAN, initForm);
        return outForm;
    }

    public BaseOutForm procAdd(ActionRequest request, Map<String, Object> reqMap, ValidationConf validationConf,
                               ActionResponse response) throws PortletException, IOException {
        LOG.debug("procAdd.START");
        
     // Parse map of request into form bean
        AddInForm form = (AddInForm) ReqUtil.getData(reqMap, AddInForm.class, validationConf);
        
        // Keep data input on the screen
        outForm.putRequest(AddInForm.FORM_BEAN, form);
        
        if ((form.getErrors() != null) && (form.getErrors().size() > 0)) {
            LOG.debug("Errors " + form.getErrors().size() + ". Re-display the Add screen to display error");
            
            outForm.putRequest("errors", form.getErrors());
            //outForm.putRequest(K_ERROR, "Data is not valid.");
            outForm.setNextResult("fail");
        } else {
            LOG.debug("Setting result OK");
            DataFormBiz biz = new DataFormBiz();
            biz.addUser(form);
            outForm.setNextResult("success");
            
            outForm.putRequest("users", biz.getUsers());
            
            outForm.putRequest(K_MESSAGE, "Save successfully.");
        }

        LOG.debug("procAdd.END");
        return outForm;
    }
    
    /**
     * Process List event.
     * @param request
     * @param reqMap
     * @param response
     * @return
     * @throws PortletException
     * @throws IOException
     */
    public BaseOutForm procList(ActionRequest request, Map<String, Object> reqMap, ActionResponse response)
    throws PortletException, IOException {
        DataFormBiz biz = new DataFormBiz();
        BaseOutForm outForm = new BaseOutForm();
        outForm.putRequest("USERS", biz.getUsers());
        
        return outForm;
    }
    
//    /**
//     * Simple data validation. It convert data form into entity if data is valid.
//     * @param form
//     * @return
//     */
//    User validate(AddInForm form, BaseOutForm outForm) {
//        if (!CommonUtil.isNNandNB(form.getUsername())) {
//            return null;
//        }
//        
//        if (!CommonUtil.isNNandNB(form.getBirthday())) {
//            return null;
//        }
//        
//        Date birthday = CommonUtil.parse(form.getBirthday(), DATE_FMT); 
//        if (birthday == null) {
//            return null;
//        }
//        
//        User user = new User();
//        user.setUsername(form.getUsername());
//        user.setBirthday(birthday);
//        
//        
//        // debug upload filed
//        LOG.debug(form.getAttachedFile());
//        FileItem attachedFile = form.getAttachedFile(); 
//        if (attachedFile != null) {
//            LOG.debug("Attached file: " + attachedFile);
//            try {
//                // Create rootPath folder if it not existed.
//                File rootPathFile = new File(form.getRootPath());
//                if (!rootPathFile.exists()) {
//                    if (!rootPathFile.mkdirs()) {
//                        outForm.putRequest(K_ERROR, "Could not create folder '" + form.getRootPath() + "' on server.");
//                    }
//                }
//                String filePath = attachedFile.getName();
//                int lastSlashChar = attachedFile.getName().lastIndexOf("\\");
//                String fileName = (lastSlashChar > 0) ? filePath.substring(lastSlashChar) : filePath;
//                
//                // Save attached file.
//                attachedFile.write(new File(form.getRootPath() + File.separatorChar +  fileName));
//                LOG.debug("Saved file '" + form.getRootPath() + File.separatorChar +  fileName + "'");
//            } catch (Exception ex) {
//                LOG.debug(ex);
//            }
//        }
//        
//        return user;
//    }
    
    
}

